﻿using ServiceStack;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Text;

namespace unvs.human
{
    public class HumanController:Service
    {
        public object Get(HumanRequest Data)
        {
            try
            {
                var db = new unvs.human.db();
                var type = typeof(unvs.human.db).Assembly.GetExportedTypes().FirstOrDefault(p => p.Name.ToLower() == Data.Entity.ToLower());
                var sql="Select * from " + Data.Entity;
                if(! string.IsNullOrEmpty(Data.Filter)){
                    sql=sql+" Where "+Data.Filter;
                }
                var data = db.Database.SqlQuery(type, sql).Cast<object>();
                return new HumanResponse()
                {
                  
                    Data = data
                };
            }
            catch (Exception ex)
            {
                return new HumanResponse()
                {
                    Message = ex.Message,
                    Exception=ex,
                    IsError=true
                };
            }
        }
        public object Get(HumanItemRequest Data)
        {
            var db = new unvs.human.db();
            var type = typeof(unvs.human.db).Assembly.GetExportedTypes().FirstOrDefault(p => p.Name.ToLower() == Data.Entity.ToLower());

            var data = db.Database.SqlQuery(type, "Select * from " + Data.Entity+" Where PersonID={0}",Data.ID).Cast<object>().FirstOrDefault();
           
            return new HumanItemResponse()
            {
                ID=Data.ID,
                Data=data
            };
        }
    }
    public static class MyExtensions
    {
        public static string GetEntitySetName<T>(this ObjectContext context)
        {
            string className = typeof(T).Name;

            var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
            string entitySetName = (from meta in container.BaseEntitySets
                                    where meta.ElementType.Name == className
                                    select meta.Name).First();

            return entitySetName;
        }
    }
}
